package com.example.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.Random;

//@Data
//@AllArgsConstructor
//@Component
public class SendSmsExample {
    //    // 阿里云短信服务的区域ID
//    private static final String REGION_ID = "cn-hangzhou";
//    // 你的AccessKey ID
//    private static final String ACCESS_KEY_ID = "your_access_key_id";
//    // 你的AccessKey Secret
//    private static final String ACCESS_KEY_SECRET = "your_access_key_secret";
    private String regionId;
    private String accessKeyId;
    private String accessKeySecret;

    public static boolean SendCode(String phone, String code) {
        System.out.println("已向手机号" + phone + "发送code成功：" + code);
        return true;
    }

    public static String generateVerificationCode(int length) {
        String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder verificationCode = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            verificationCode.append(charSet.charAt(random.nextInt(charSet.length())));
        }
        System.out.println(verificationCode);
        return verificationCode.toString();
    }

    public boolean SendCode_2(String phone, String code) throws com.aliyuncs.exceptions.ClientException {
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phone);
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_318845764");
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            if ("OK".equals(response.getCode())) {
                System.out.println("短信发送成功");
                return true;
            } else {
                System.out.println("短信发送失败，ErrorCode: " + response.getCode() + ", ErrorMessage: " + response.getMessage());
                // 根据不同的错误码进行更详细的处理
                if ("isv.MOBILE_NUMBER_ILLEGAL".equals(response.getCode())) {
                    System.out.println("手机号码非法，请检查输入");
                    return false;
                }
            }
        } catch (ClientException e) {
            System.out.println("短信发送失败，ErrorMsg: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}

